package com.htzos.common.interceptor;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.htzos.admin.log.bean.LogReqBase;
import com.htzos.admin.log.service.LogReqBaseService;
import com.htzos.admin.system.bean.SystemUserBase;
import com.htzos.common.util.CommonUtil;

/**
 * 通用的拦截器，主要用来记录访问日志
 *
 * @author xudz
 * @time 2017 2017年1月18日 上午10:20:59
 */
public final class CommonInterceptor extends HandlerInterceptorAdapter {

	private Logger logger=Logger.getLogger(CommonInterceptor.class);
	
	@Resource
	private LogReqBaseService logReqBaseService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		return  super.preHandle(request, response, handler);
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
		//设置调用的地址
		super.postHandle(request, response, handler, modelAndView);
	};
	
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		
		String url= request.getScheme()+"://"; //请求协议 http 或 https    
		url+=request.getHeader("host");  // 请求服务器    
		url+=request.getRequestURI();     // 工程名      
	    String ipAddress = null;
	     //ipAddress = request.getRemoteAddr();
	    ipAddress = request.getHeader("x-forwarded-for");
	    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	      ipAddress = request.getHeader("Proxy-Client-IP");
	    }
	    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	      ipAddress = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
		  ipAddress = request.getRemoteAddr();
		  if(ipAddress.equals("127.0.0.1")){
		       //根据网卡取本机配置的IP
		    InetAddress inet=null;
		    try {
			    	inet = InetAddress.getLocalHost();
		    } catch (UnknownHostException e) {
			     e.printStackTrace();
			}
			ipAddress= inet.getHostAddress();
		  }
	         
	   }
	
	     //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
	     if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
	         if(ipAddress.indexOf(",")>0){
	             ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
	         }
	     }
		 
		 StringBuffer params=new StringBuffer("");
	     Map map=request.getParameterMap();  
	     Set keSet=map.entrySet();  
	     for(Iterator itr=keSet.iterator();itr.hasNext();){  
	         Map.Entry me=(Map.Entry)itr.next();  
	         Object ok=me.getKey();  
	         Object ov=me.getValue();  
	         String[] value=new String[1];  
	         if(ov instanceof String[]){  
	             value=(String[])ov;  
	         }else{  
	             value[0]=ov.toString();  
	         }  
	   
	         for(int k=0;k<value.length;k++){  
	             params.append(ok+"="+value[k]+";");  
	         }  
	     }  
	     
	    HttpSession session = request.getSession();
	    SystemUserBase user = (SystemUserBase)session.getAttribute(CommonUtil.CURRENTUSER);
	     
        LogReqBase logReqBase=new LogReqBase();
        logReqBase.setReqtime(new Date());
        logReqBase.setIp(ipAddress);
        logReqBase.setPage(url);
        logReqBase.setAccount(user==null?null:user.getAccount());
        logReqBase.setParams(params.toString());
        //保存日志
        logReqBaseService.logReqBaseInsert(logReqBase);
	}
}

